import { createRouter, createWebHashHistory } from "vue-router";
import layoutRoutes from "./layoutRoutes";
import { getCookie } from "@/utils/cookie";
import { checkUserInfo, getMenuList, setBrowserTitle } from "./tools";

const router = createRouter({
  history: createWebHashHistory(),
  // 加载所有路由
  routes: layoutRoutes,
});

router.beforeEach(async (to, _from, next) => {
  // 登录状态
  const token = getCookie("token");

  if (!token && !["Login", "Logout"].includes(<string>to.name)) {
    next({
      name: "Login",
    });
    return false;
  }

  // 设置对应路由的浏览器标签标题
  setBrowserTitle(to);

  // 获取菜单
  getMenuList(to);

  // 获取用户信息
  await checkUserInfo(to);

  next();
});

export default router;
